# !/bin/python

import numpy as np
from time import localtime, strftime
from scipy import sparse
import sys


def now():
    return strftime("%Y-%m-%d %H:%M:%S", localtime())


def error(s):
	print >> sys.stderr, s

def matrix_from_file(path, mtx_shape):
	edges = np.loadtxt(path)
	row_indices = edges[:, 0]
	col_indices = edges[:, 1]
	vals        = edges[:, 2]
	mtx = sparse.csr_matrix((vals, (row_indices, col_indices)),  shape = mtx_shape, dtype=float)
	return mtx

def write_file(filepath, mtx):
	indices = mtx.nonzero()
	row_indices = indices[0]
	col_indices = indices[1]
	vals = (mtx[row_indices, col_indices].A)[0]
	# vals = vals.toarray()[0]
	assert len(row_indices) == len(col_indices) == len(vals)
	fh = file(filepath, 'wb')
	for i in xrange(len(vals)):
		fh.write("%d %d %f\n"%(row_indices[i], col_indices[i], vals[i]))
	fh.close()

def mask(maskcode, matrix):
	mask_code_mtx = np.where(maskcode.A != 0, 1, 0)
	return matrix.multiply(mask_code_mtx)



# alpha = float(sys.argv[1])
attr_sim_path = sys.argv[1]
tran_sim_path = sys.argv[2]

# locality = 5
num_row = 6349
num_col = 6349
#num_row = 3953
#num_col = 3953
mtx_shape = (num_row, num_col)

error( now()+' reading %s...'%attr_sim_path)
attr_sim = matrix_from_file(attr_sim_path, mtx_shape)

error( now()+' reading %s...'%tran_sim_path)
tran_sim = matrix_from_file(tran_sim_path, mtx_shape)

attr_sim = mask(tran_sim, attr_sim).tocsr()

for alpha in [0,1,0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]:
	error(now() + ' merging %s...'%alpha)
	merged_sim = alpha*tran_sim + (1-alpha) * attr_sim
	# writing
	outfilepath = 'merged_net_%s.tmp'%alpha
	error(now() + ' writing into %s'%outfilepath)
	write_file(outfilepath, merged_sim)
	# done promote
	error(now() + ' done.')
